<?php
function array_length($arr){
    $length = 0;
    foreach($arr as $key=>$value){
        $length++;
    }
    return $length;
}

function array_implode($arr,$needle=','){
    $length = array_length($arr);
    $str="";
    $i = 0;
    while($i<$length){
        $inst = $arr[$i];
        //$str .=$interests[$i];
        $str = $str.$inst.$needle;
        $i++;
    }
    return $str;
}

$hasError=false;

//检查用户名
//必须填写
//填写规则
$username = trim($_POST["Username"]);
if(!$username){
     echo "用户名不能为空!</br>";
     $hasError=true;
}else{
    $len = strlen($username);
    if($len<3){
        echo"用户名至少要有3个字符<br/>";
        $hasError=true;
    }else if($len>5){
        echo "用户名最多五个字符<br/>";
        $hasError=true;
    }else if(!preg_match('/^[a-zA-Z0-9_]*$/',$username)){
        echo "格式不符合要求!";
        $hasError=true;
    }
}

//检查密码
//必须填写
//填写规则
$pswd = trim($_POST["Password"]);
if(!$pswd){
    echo "密码不能为空!</br>";
    $hasError=true;
}else{
    $len = strlen($pswd);
    if($len<3){
        echo "密码至少要有3个字符<br/>";
        $hasError=true;
    }else if($len>5){
        echo "密码最多只有5个字符<br/>";
        $hasError=true;
    }
}

//年龄
//可以不填写
//填写规则
$age=trim($_POST["Age"]);
if($age){
    //  '/^\d+$/'
    $ageNum=intval($age);
    if(!$ageNum || $ageNum<=0 || $ageNum>200){
        echo"请输入正确的年龄!<br/>";
        $hasError=true;
    }
}

//兴趣
//必须填写
//填写规则
$interests = $_POST["interests"];
$length = array_length($interests);
if($length<2){
    echo "兴趣必须选择两项<br/>";
    $hasError=true;
}else if($length>3){
    echo "兴趣最多选择三项<br/>";
    $hasError=true;
}
$interestsStr = array_implode($interests);
//var_dump($_POST);
$gender = $_POST["gender"];
$province = $_POST["province"];
$intro = $_POST["intro"];

if(!$hasError){
    $intro = str_replace("'","''",$intro);
    $sql = "INSERT INTO Account(Username,Password,Gender,Interests,Province,Intro)VALUES('$username','$pswd','$gender','$interestsStr','$province','$intro')";
    echo $sql;

    $sqli = new mysqli("localhost","root","","myblog");
    $sqli->query($sql);
    echo "注册成功!<br/>";
    //echo mysqli_error($sqli);
}

echo "<a href='test_6_complexform.html'>返回</a>";
?>